package com.waimai.app.qa.mail;

import java.util.ArrayList;
import java.util.Date;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * Send Mail
 * @author AiHui
 */
public class SendMail extends Authenticator {

	private IMailInfo minfo;
	private Session sendMailSession;

	public SendMail(IMailInfo info) {
		minfo = info;
		if (minfo.getValidate()) {
			getPasswordAuthentication();
			sendMailSession = Session.getDefaultInstance(minfo.getProperties(), this);
		} else {
			sendMailSession = Session.getDefaultInstance(minfo.getProperties());
		}
	}

	public boolean sendStart() {
		try {
			// 根据session创建一个邮件消息
			Message mailMessage = new MimeMessage(sendMailSession);
			// 设置邮件消息的发送者
			mailMessage.setFrom(new InternetAddress(minfo.getFromAddress()));
			// 创建邮件的接收者地址，并设置到邮件消息中
			// 分解多个发送的邮件地址
			String[] toAddresses = minfo.getToAddress().split(";");
			ArrayList<InternetAddress> adds = new ArrayList<InternetAddress>();
			for (String a : toAddresses) {
				if (!a.isEmpty()) {
					adds.add(new InternetAddress(a));
				}
			}
			InternetAddress[] addss = new InternetAddress[adds.size()];
			mailMessage.setRecipients(Message.RecipientType.TO,
					adds.toArray(addss));
			// 设置邮件消息的主题
			mailMessage.setSubject(minfo.getSubject());
			// 设置邮件消息发送的时间
			mailMessage.setSentDate(new Date());
			if (minfo.getContentType().equalsIgnoreCase("html")) {
				// MiniMultipart类是一个容器类，包含MimeBodyPart类型的对象
				Multipart mainPart = new MimeMultipart();
				// 创建一个包含HTML内容的MimeBodyPart
				BodyPart html = new MimeBodyPart();
				// 向Multipart添加附件
				for(String filename:minfo.getAttachment()){
					MimeBodyPart mbpFile = new MimeBodyPart();
					FileDataSource fds = new FileDataSource(filename);
					mbpFile.setDataHandler(new DataHandler(fds));
					mbpFile.setFileName(filename);
					// 向MimeMessage添加（Multipart代表附件）
					mainPart.addBodyPart(mbpFile);
				}
				minfo.clearAttachment();
				// 设置HTML内容
				html.setContent(minfo.getContent(), "text/html; charset=utf-8");
				mainPart.addBodyPart(html);
				// 将MiniMultipart对象设置为邮件内容
				mailMessage.setContent(mainPart);
			} else {
				mailMessage.setText(minfo.getContent());
			}
			// 发送邮件
			Transport.send(mailMessage);
			return true;
		} catch (MessagingException ex) {
			ex.printStackTrace();
		}
		return false;
	}

	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(minfo.getUserName(),
				minfo.getPassword());
	}
}
